package com.ljh.service;

import com.ljh.sale.entity.Orders;
import com.ljh.sale.entity.Sku;
import com.ljh.sale.entity.Stock;
import com.ljh.sale.service.OrdersService;
import com.ljh.sale.service.SkuService;
import com.ljh.sale.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.OrderComparator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * Created by DELL on 2018/10/24.
 */
@Service("service")
public class SaleService {

    @Autowired
    private SkuService skuService;
    @Autowired
    private StockService stockService;
    @Autowired
    private OrdersService ordersService;

    @Transactional
    public void sale(Long skuId){
        Sku sku = skuService.findSkuBySkuId(skuId);
        if (sku == null) {
            return;
        }
        Stock stock = stockService.findBySkuId(skuId);
        if (stock != null) {
            if (stock.getAmount() > 0 && stock.getStatus().equals(1)) {
                stock.setAmount(stock.getAmount() - 1);
                stockService.update(stock);
                Orders orders = new Orders();
                orders.setSkuName(sku.getName());
                orders.setSkuId(skuId);
                orders.setOriginalPrice(sku.getPrice());
                orders.setNum(1);
                orders.setTotalPrice(sku.getPrice());
                orders.setDiscount(0L);
                orders.setFinalPrice(sku.getPrice());
                orders.setStatus(1);
                orders.setCreateTime(System.currentTimeMillis());
                orders.setOrderNumber(UUID.randomUUID().toString());
                orders.setCreateBy("");
                ordersService.save(orders);

            }
        }
    }

}